use anyhow::Result;
use play_api::{AuthDB, AuthInfo, OfflineAuth};
use play_auth_offline::OfflinePlayer;
use play_db::DB;
use tempfile::NamedTempFile; // 用于创建临时数据库文件

// 集成测试
#[test]
fn test_offline_player_auth() -> Result<()> {
    // 创建临时文件用于测试数据库
    let tmp_file = NamedTempFile::new()?;
    let tmp_path = tmp_file.path();
    let db_path = tmp_path.to_str().unwrap();

    // 初始化数据库
    let db = DB::new(db_path);

    // 创建测试玩家
    let player_name = "Steve";
    let player = OfflinePlayer::to_auth(player_name, None);

    // 保存玩家信息
    db.save_auth(player.clone())?;

    // 获取玩家信息
    let retrieved_player = db.get_auth(player_name)?.expect("Player should exist");

    // 验证信息是否正确
    assert_eq!(player.username, retrieved_player.username);
    assert_eq!(player.uuid, retrieved_player.uuid);
    assert_eq!(player.access_token, retrieved_player.access_token);
    assert_eq!(player.refresh_token, retrieved_player.refresh_token);
    assert_eq!(player.is_online, retrieved_player.is_online);

    Ok(())
}

#[test]
fn test_list_all_auth() -> Result<()> {
    // 创建临时文件用于测试数据库
    let tmp_file = NamedTempFile::new()?;
    let tmp_path = tmp_file.path();
    let db_path = tmp_path.to_str().unwrap();

    // 初始化数据库
    let db = DB::new(db_path);

    // 创建多个测试玩家
    let players = vec!["Steve", "Alex", "Creeper"];

    for (i, player_name) in players.iter().enumerate() {
        let player = OfflinePlayer::to_auth(player_name, None);
        // 保存玩家信息
        db.save_auth(player)?;
    }

    // 获取所有玩家信息
    let all_players = db.list_all_auth()?;

    // 验证数量是否正确
    assert_eq!(all_players.len(), 3);

    // 验证每个玩家是否存在
    for player_name in players {
        assert!(all_players.iter().any(|p| p.username == player_name));
    }

    Ok(())
}

#[test]
fn test_remove_auth() -> Result<()> {
    // 创建临时文件用于测试数据库
    let tmp_file = NamedTempFile::new()?;
    let tmp_path = tmp_file.path();
    let db_path = tmp_path.to_str().unwrap();

    // 初始化数据库
    let db = DB::new(db_path);

    // 创建测试玩家
    let player_name = "Steve";
    let player = OfflinePlayer::to_auth(player_name, None);

    // 保存玩家信息
    db.save_auth(player.clone())?;

    // 验证玩家存在
    assert!(db.get_auth(player_name)?.is_some());

    // 删除玩家
    db.remove_auth(player_name)?;

    // 验证玩家已删除
    assert!(db.get_auth(player_name)?.is_none());

    Ok(())
}
